/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package main;

import java.sql.*;

/**
 *
 * @author boomar
 */
public class ConnectBDD {

    private String driver = "com.mysql.jdbc.Driver";
    private String url = "jdbc:mysql://172.19.4.2:3306";
    private String user = "CAR1";
    private String password = "CAR1";

    public ConnectBDD() {
    }

    public ConnectBDD(String driver, String url, String user, String password) {
        this.driver = driver;
        this.url = url;
        this.user = user;
        this.password = password;
    }

    public ResultSet execQuery(String query) throws SQLException {

        try {
            Class.forName(this.driver);
        } catch (Exception ex) {
            return null;
        }

        Connection cx = DriverManager.getConnection(this.url, this.user, this.password);
        Statement st = cx.createStatement();

        try {
            ResultSet rs = st.executeQuery(query);
            rs.close();
            return rs;
        } catch (SQLException ex) {
            return null;
        } finally {
            st.close();
            cx.close();
            return null;
        }
    }

    public ListEleve getListEleve() throws SQLException {

        ListEleve listeArticles = new ListEleve();

        ResultSet rs = execQuery("SELECT * FROM ED_JDBC.eleves");

        while (rs.next()) {
            listeArticles.add(new Eleve(rs.getInt("ideleve"), rs.getString("nom"), rs.getString("prenom"), rs.getDate("anneeInscription"),rs.getInt("idpromo")));
        }

        return listeArticles;
    }

    public ListPromotion getListPromotion() throws SQLException {

        ListPromotion listePromotion = new ListPromotion();

        ResultSet rs = execQuery("SELECT * FROM ED_JDBC.promotion");

        while (rs.next()) {
            listePromotion.add(new Promotion(rs.getInt("idpromotion"), rs.getDate("annee"), rs.getString("typeformation"), rs.getString("niveau")));
        }

        return listePromotion;
    }

    public Utilisateur getUtilisateur(String login, String password) throws SQLException {

        String q="SELECT * FROM ED_JDBC.utilisateur WHERE login='"+login+"' AND password='"+password+"'";

        ResultSet rs = execQuery(q);

        return rs == null ? null : new Utilisateur(rs.getInt("idutilisateur"), rs.getString("login"), rs.getString("password"), rs.getString("nom"), rs.getString("prenom"));
    }
}
